﻿using System;
using System.Globalization;


namespace Iworld.Toolkit.Converter
{
    /// <summary>
    /// 转换器基类,统一处理空值(null)的情况
    /// </summary>
    /// <typeparam name="SourceType">绑定源的类型</typeparam>
    /// <typeparam name="TargetType">绑定目标的类型</typeparam>
    public abstract class ConverterBase<SourceType, TargetType> : AbstractConverter
    {

        /// <summary>
        /// 子类实现由绑定源到绑定目标的转换,value不会为null
        /// </summary>
        /// <param name="value"></param>
        protected abstract TargetType ConvertNotNull(SourceType value, Type targetType, object parameter ,CultureInfo culture);

        /// <summary>
        /// 子类实现由绑定目标到绑定源的转换,value不会为null
        /// </summary>
        /// <param name="value"></param>
        protected abstract SourceType ConvertBackNotNull(TargetType value, Type targetType, object parameter,CultureInfo culture);


        public sealed override object Convert(object value, Type targetType, object parameter,CultureInfo culture)
        {
            if (IsNull(value, parameter, culture)) return GetConvertNullValue(targetType, parameter);
            return ConvertNotNull((SourceType)value, targetType, parameter, culture);
        }

  
        public sealed override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (IsNull(value, parameter, culture)) return GetConvertBackNullValue(targetType, parameter);
            return ConvertBackNotNull((TargetType)value, targetType, parameter, culture);
        }

        /// <summary>
        /// 判断是否为空
        /// </summary>
        /// <param name="value"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        protected virtual bool IsNull(object value,object parameter ,CultureInfo culture)
        {
            return value == null;
        }

        /// <summary>
        /// 获取绑定目标的默认空值
        /// </summary>
        protected virtual TargetType GetConvertNullValue(Type targetType, object parameter)
        {
            return default(TargetType);
        }

        /// <summary>
        /// 获取绑定源的默认空值
        /// </summary>
        protected virtual SourceType GetConvertBackNullValue(Type targetType, object parameter)
        {
            return default(SourceType);
        }
    }
}
